/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Servlets;

import Beans.beanClave;
import Conexion.cConexion;
import Sesion.Sesion;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Emanuel
 */
public class srvClave extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            
            
            String envicorreo = request.getParameter("envicorreo");

            String[] email = Sesion.getFila("select correo_pe from personal where correo_pe='" + envicorreo + "' ");

            if (email == null) {

                out.println("<!DOCTYPE html>");
                out.println("<html>");
                out.println("<head>");
                out.println("<title> :::EL CORREO NO EXISTE!::: </title>");
                out.println("<link rel='stylesheet' href='CSS/Styles.css' type='text/css'/>");
                out.println("</head>");
                out.println("<body>");
                out.println("<div id='header'>");
                out.println("<h1>El Correo No Existe!</h1>");
                out.println("<h2>Laboratorio de Ciencias Basicas</h2>");
                out.println("</div>");
                out.println("<hr id='header_stripe'>");
                out.println("<div id='page_container'>");
                out.println("<a href='Clave/RecuperarClave.jsp'><img src='IMAGES/logoufg2012.png' width='350px' height='350px'/></a>");
                out.println("<h2>Click sobre la imagen para volver a intentar</h2>");                
                out.println("</div>");
                out.println("</body>");
                out.println("</html>");

            } else {
                try {
                    //realiza la coneccion
                    Connection cnn = cConexion.conectar_ds();
                    PreparedStatement psta;
                    //llama a la accion de el bean
                    psta = cnn.prepareStatement(beanClave.modclave);
                    //captura el dato y lo perara para enviar
                    psta.setString(1, envicorreo);
                    //ejecuta la accion del bean
                    psta.executeUpdate();





                } catch (SQLException e) {
                    out.println(e.getMessage());
                }

                String[] nueva = Sesion.getFila("select clave, correo_pe from personal where correo_pe= '" + envicorreo + "'  ");

                String clave = nueva[0];
                String correo = nueva[1];

                //String email = (String) request.getParameter("correo");    
                //start of email code::
                final String username = "servisioscienciasbasicasufg@gmail.com";
                final String password = "!ufg!asi";

                Properties props = new Properties();
                props.put("mail.smtp.auth", "true");
                props.put("mail.smtp.starttls.enable", "true");
                props.put("mail.smtp.host", "smtp.gmail.com"); //este es la direccion del servidor smtp
                props.put("mail.smtp.port", "587"); // este es el puerto del servidor smtp
                props.setProperty("mail.smtp.ssl.trust", "smtp.gmail.com");

                Session sesion = Session.getInstance(props,
                        new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(username, password); //esto se usa para autenticar
                    }
                });

                try {
                    Message mesage = new MimeMessage(sesion);
                    mesage.setFrom(new InternetAddress("servisioscienciasbasicasufg@gmail.com")); // quien envia el correo
                    mesage.setRecipients(Message.RecipientType.TO,
                            InternetAddress.parse(correo)); //destinatario de correo
                    mesage.setSubject("Recuperación de contraseña"); // asunto del correo
                    mesage.setContent("<h1>HA RESTABLECIDO SU CONTRASEÑA</h1><br><h3>su nueva clave es: <b>" + clave + "</b>  </h3>", "text/html; charset=utf-8"); //el contenido del correo
                    Transport.send(mesage); //envia el correo completo

                    //out.println("el correo se envio bien"); //verifica que se envio correctamente

                } catch (MessagingException e) {
                    throw new RuntimeException(e); // si el correo esta mal o no existe
                }
                //fin del email
                
                response.sendRedirect("index.jsp");
            }
        } finally {            
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
